import $http from '@/api'
function jsApiCall(orderId) {
  let data = window.signData.data
  if (!data) {
    window.location.href = '/'
    return
  }
  /* eslint-disable */
  WeixinJSBridge.invoke('getBrandWCPayRequest', {
    appId: data.appId,
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.package,
    signType: data.signType,
    paySign: data.paySign
  }, (res) => {
    let jumpurl = '/payment_status?orderid=' + orderId
    if (res.err_msg === 'get_brand_wcpay_request:ok' || res.err_msg === 'get_brand_wcpay_request:cancel') {
      location.href = jumpurl
    } else {
      alert(res.err_code + res.err_desc + res.err_msg)
      location.href = jumpurl
    }
  })
}

function callpay(orderId) {
  // location.href = '/payment_status?orderid=' + orderId
  if (typeof WeixinJSBridge === undefined) {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', jsApiCall, false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', jsApiCall)
      document.attachEvent('onWeixinJSBridgeReady', jsApiCall)
    }
  } else {
    jsApiCall(orderId)
  }
}

export default {
  payAjax: function(orderId) {
    if (!orderId) {
      window.location.href = '/'
      return
    }
    $http.payCallPay(orderId)
    .then(res => {
      if (res.code === 0) {
        window.signData = res.data
        callpay(orderId)
      } else {
        alert(res.msg)
      }
    })
    // .catch((err) => {
    //   alert('系统异常,请刷新重试')
    // })
  }
}
